import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PordComsumedemoPlus {

    public static void main(String[] args) {
        MyPrintPlus myPrintPlus = new MyPrintPlus();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                myPrintPlus.print2();
            }
        }, "t1: ").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                myPrintPlus.print3();
            }
        }, "t2: ").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                myPrintPlus.print4();
            }
        }, "t3: ").start();
    }

}

class MyPrintPlus {

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    private int flag = 1;

    public void print2() {
        lock.lock();
        try {
            while (flag != 1) condition1.await();
            for (int i = 1; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + i);
            }
            flag = 2;
            condition2.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void print3() {
        lock.lock();
        try {
            while (flag != 2) condition2.await();
            for (int i = 1; i < 4; i++) {
                System.out.println(Thread.currentThread().getName() + i);
            }
            flag = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void print4() {
        lock.lock();
        try {
            while (flag != 3) condition3.await();
            for (int i = 1; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + i);
            }
            flag = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

}